package term

import (
	"context"

	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetTermByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetTermByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTermByIdLogic {
	return &GetTermByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetTermByIdLogic) GetTermById(req *types.IDReq) (resp *types.MediaTermInfoResp, err error) {
	data, err := l.svcCtx.AttachmentRpc.BackendGetTermById(l.ctx, &attachmentclient.TermIdReq{
		Id:       req.Id,
		WithMeta: pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, err
	}

	var meta []*types.MetaInfo
	if len(data.Meta) > 0 {
		for _, v := range data.Meta {
			meta = append(meta, &types.MetaInfo{
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	option := utils.GetOptionByStatus(data.Status)

	return &types.MediaTermInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.MediaTermInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Name:     data.Name,
			Slug:     data.Slug,
			Taxonomy: data.Taxonomy,
			ParentId: data.ParentId,
			GroupId:  data.GroupId,
			Desc:     data.Desc,
			Sort:     data.Sort,
			Status:   data.Status,
			Count:    data.Count,
			Meta:     meta,
		},
	}, nil
}
